#include <QtWidgets>
#include "../../DebugTools/DebugTool.h"

void init(QTreeWidget *w){
  w->setHeaderLabels ({"节点","内容"});
  QList<QTreeWidgetItem *> list;

  // 3 行 2列，每行2个子节点
  for (int i = 0; i < 3; ++i) {
    QTreeWidgetItem *item = new QTreeWidgetItem(w);
//    item->setFlags (Qt::ItemIsEditable | item->flags ());
    cout << item->flags ();
    item->setExpanded (true); // 只有设置了父控件，才能展开
    list << item;
    item->setText (0,QString("父节点%1").arg (i));
    item->setText (1,item->text (0));

    for (int j = 0; j < 2; ++j) {
      QTreeWidgetItem *child = new QTreeWidgetItem(item);
//      child->setFlags (Qt::ItemIsEditable | item->flags ());
      child->setText (0,QString("子节点%1-%2").arg (i).arg(j));
      child->setText (1,child->text (0));
    }
  }
  w->addTopLevelItems (list);
  w->resize (300,300);
  w->resizeColumnToContents (1);
//  w.header ()->setSectionsClickable (false);
  w->header ()->setSectionResizeMode (0,QHeaderView::Stretch );
//  w.setEditTriggers (QTreeWidget::DoubleClicked );
}

void setSignSlots(QTreeWidget *w){
  QObject::connect (w,&QTreeWidget::itemDoubleClicked,
                   [w](QTreeWidgetItem *item){
                     QStringList list;
                     if(item->childCount ()==0){
                       list.push_front (item->text (0));
                       while (item->parent ()) {
                         item = item->parent ();
                         list.push_front (item->text (0));
                       }
                       cout << list;
                     }
  });
}


void setDragAndDrop(QTreeWidget *w){
  w->setDragEnabled (true);              // 启用拖动
  w->viewport ()->setAcceptDrops (true); // viewport 接受放下动作，默认是复制操作
  w->showDropIndicator ();               // 设置放下指示
  w->setDragDropMode (QTreeWidget::InternalMove);// 内部 移动
}

void setSelectionMode(QTreeWidget *w){
  w->setSelectionBehavior (QTreeWidget::SelectRows);     // 选择行
  w->setSelectionMode (QTreeWidget::ContiguousSelection);// 连续选择
}

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  QTreeWidget w;
  // 初始化Tree
  init (&w);
  // 设置Tree的拖放
  setDragAndDrop(&w);
  // 设置Tree的选定模式和行为
  setSelectionMode (&w);

  setSignSlots (&w);
  w.show ();
  return a.exec();
}
